<template>
  <view class="outbound-execute">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-orange" :isBack="true">
      <block slot="content">执行出库</block>
    </cu-custom>

    <!-- 头部信息 -->
    <view class="header-section">
      <view class="order-info">
        <text class="order-title">{{
          outboundDetail.outboundNo || "出库单详情"
        }}</text>
        <view class="status-badge" :class="statusClass">
          <text class="status-text">{{ statusText }}</text>
        </view>
      </view>
      <view class="order-details">
        <text class="detail-text"
          >出库单号: {{ outboundDetail.orderNo || "-" }}</text
        >
        <text class="detail-text"
          >客户名称: {{ outboundDetail.customerName || "-" }}</text
        >
        <text class="detail-text"
          >项目名称: {{ outboundDetail.projectName || "-" }}</text
        >
        <text class="detail-text"
          >计划总数: {{ outboundDetail.totalQuantity || 0 }}套</text
        >
      </view>
    </view>

    <!-- 出库明细 -->
    <view class="detail-card">
      <view class="card-header">
        <text class="card-title">出库明细</text>
        <text class="detail-count">共{{ detailList.length }}项</text>
      </view>
      <view class="detail-list">
        <view
          v-for="(item, index) in detailList"
          :key="index"
          class="detail-item"
        >
          <view class="item-header">
            <view class="window-info">
              {{ item.windowNo || `明细${index + 1}` }}
            </view>
            <view class="quantity">{{ item.availableQuantity }}套</view>
          </view>
          <view class="item-content">
            <view class="detail-row">
              <text class="detail-label">门窗编号:</text>
              <text class="detail-value">{{ item.windowNo || "-" }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">门窗系列:</text>
              <text class="detail-value">{{ item.windowSeries || "-" }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">门窗颜色:</text>
              <text class="detail-value">{{ item.windowColor || "-" }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">计划数量:</text>
              <text class="detail-value">{{ item.availableQuantity }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">所在仓库:</text>
              <text class="detail-value">{{ item.warehouseName || "-" }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">所在库位:</text>
              <text class="detail-value">{{ item.locationName || "-" }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section">
      <view class="summary-info">
        <text class="summary-text"
          >本次出库: {{ getTotalOutboundQuantity() }}套</text
        >
      </view>
      <view class="action-buttons">
        <button class="cu-btn bg-gray lg" @click="goBack">取消</button>
        <button
          class="cu-btn bg-orange lg"
          @click="executeOutbound"
          :disabled="!canExecuteOutbound"
        >
          确认出库
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getOutboundDetail,
  getOutboundExecuteDetailList,
  executeOutbound as executeOutboundApi,
  executeBatchOutbound as executeBatchOutboundApi,
  getWarehouseList,
  getLocationList,
} from "@/api/wms/finishedGoodsOutbound.js";

export default {
  name: "OutboundExecute",
  data() {
    return {
      loading: false,
      outboundId: "",
      outboundDetail: {},
      detailList: [],
      warehouseList: [],
      locationList: {},
    };
  },
  computed: {
    statusClass() {
      if (!this.outboundDetail) return "status-pending";
      const statusMap = {
        0: "status-pending",
        1: "status-approved",
        2: "status-partial",
        3: "status-completed",
        4: "status-cancelled",
      };
      return statusMap[this.outboundDetail.status] || "status-pending";
    },
    statusText() {
      if (!this.outboundDetail) return "待审核";
      const statusMap = {
        0: "待审核",
        1: "已审核",
        2: "部分出库",
        3: "已完成",
        4: "已取消",
      };
      return statusMap[this.outboundDetail.status] || "待审核";
    },
    canExecuteOutbound() {
      // 检查是否有可用库存
      return this.detailList.some((item) => (item.availableQuantity || 0) > 0);
    },
  },
  onLoad(options) {
    console.log("onLoad options:", options);
    if (options.id) {
      this.outboundId = options.id;
      this.loadData();
    } else {
      uni.showToast({
        title: "参数错误",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        // 并行加载出库基本信息和明细列表
        const [detailResponse, listResponse] = await Promise.all([
          getOutboundDetail(this.outboundId),
          getOutboundExecuteDetailList(this.outboundId),
        ]);

        if (detailResponse.data.success) {
          this.outboundDetail = detailResponse.data.result;
        }

        if (listResponse.data.success) {
          // 现在API返回的是库存信息，直接显示库存信息，默认出库数量为库存数量
          this.detailList = (listResponse.data.result || [])
            .filter((item) => {
              // 过滤掉可用数量为0的库存
              return (item.availableQuantity || 0) > 0;
            })
            .map((item) => {
              return {
                ...item,
                // 设置默认出库数量为库存可用数量
                outboundQuantity: item.availableQuantity || 0,
              };
            });
        }
      } catch (error) {
        console.error("加载数据失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    async loadWarehouseList() {
      try {
        const response = await getWarehouseList({ warehouseType: 7 });
        if (response.data.success) {
          this.warehouseList = response.data.result || [];
        }
      } catch (error) {
        console.error("加载仓库列表失败:", error);
      }
    },

    async loadLocationList(warehouseId) {
      try {
        const response = await getLocationList(warehouseId);
        if (response.data && response.data.success) {
          return response.data.result || [];
        } else {
          return [];
        }
      } catch (error) {
        console.error("加载库位列表失败:", error);
        uni.showToast({
          title: "加载库位失败",
          icon: "none",
        });
        return [];
      }
    },

    // 获取计划数量（现在基于库存的可用数量）
    getPlannedQuantity(item) {
      return item.availableQuantity || 0;
    },

    // 获取剩余待出库数量（现在就是可用数量）
    getRemainingQuantity(item) {
      return item.availableQuantity || 0;
    },

    // 获取所有明细的出库总数量
    getTotalOutboundQuantity() {
      return this.detailList.reduce((total, item) => {
        return total + (item.availableQuantity || 0);
      }, 0);
    },

    // 出库数量输入处理
    onQuantityInput(itemIndex, event) {
      const value = parseInt(event.detail.value) || 0;
      const item = this.detailList[itemIndex];
      const maxQuantity = item.availableQuantity || 0;

      if (value > maxQuantity) {
        item.outboundQuantity = maxQuantity;
        uni.showToast({
          title: `最多只能出库${maxQuantity}套`,
          icon: "none",
        });
      } else if (value < 0) {
        item.outboundQuantity = 0;
      } else {
        item.outboundQuantity = value;
      }
    },

    // 调整出库数量
    adjustQuantity(itemIndex, delta) {
      const item = this.detailList[itemIndex];
      const currentQty = item.outboundQuantity || 0;
      const maxQuantity = item.availableQuantity || 0;
      const newQty = Math.max(0, Math.min(maxQuantity, currentQty + delta));

      item.outboundQuantity = newQty;
    },

    // 获取仓库名称
    getWarehouseName(warehouseIndex) {
      if (warehouseIndex >= 0 && this.warehouseList[warehouseIndex]) {
        return this.warehouseList[warehouseIndex].warehouseName;
      }
      return "请选择仓库";
    },

    // 获取库位列表
    getLocationList(warehouseId) {
      const warehouseKey = String(warehouseId);
      return this.locationList[warehouseKey] || [];
    },

    // 获取库位名称
    getLocationName(warehouseId, locationIndex) {
      if (!warehouseId) {
        return "请先选择仓库";
      }
      const locations = this.getLocationList(warehouseId);
      if (locationIndex >= 0 && locations[locationIndex]) {
        return locations[locationIndex].locationName;
      }
      return "请选择库位";
    },

    // 批次仓库选择变更
    async onBatchWarehouseChange(detailIndex, batchIndex, event) {
      const warehouseIndex = event.detail.value;
      const warehouse = this.warehouseList[warehouseIndex];
      const batch = this.detailList[detailIndex].batches[batchIndex];

      batch.warehouseId = warehouse.id;
      batch.warehouseIndex = warehouseIndex;
      batch.locationId = null;
      batch.locationIndex = -1;
      batch.quantity = 0; // 重置数量

      // 加载对应仓库的库位列表
      const locations = await this.loadLocationList(warehouse.id);
      const warehouseKey = String(warehouse.id);
      this.$set(this.locationList, warehouseKey, locations || []);
    },

    // 批次库位选择变更
    onBatchLocationChange(detailIndex, batchIndex, event) {
      const locationIndex = event.detail.value;
      const batch = this.detailList[detailIndex].batches[batchIndex];
      const item = this.detailList[detailIndex];
      const locations = this.getLocationList(batch.warehouseId);
      const location = locations[locationIndex];

      if (location) {
        batch.locationId = location.id;
        batch.locationIndex = locationIndex;

        // 选择库位后，设置数量默认值
        if (batch.warehouseId && batch.locationId && batch.quantity === 0) {
          const remainingQty = this.getRemainingQuantity(item);
          batch.quantity = Math.max(0, remainingQty);
        }
      }
    },

    // 执行出库
    async executeOutbound() {
      if (!this.canExecuteOutbound) {
        uni.showToast({
          title: "没有可出库的库存",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "一键出库中...",
        });

        // 调用一键出库接口
        const response = await this.$http.post(
          `/wms/finished-goods/outbound/one-click-outbound/${this.outboundId}`
        );

        if (response.data.success) {
          uni.showToast({
            title: "出库成功",
            icon: "success",
          });

          setTimeout(() => {
            // 通知上一级页面刷新数据
            uni.$emit("outboundExecuted");
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.data.message || "出库失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("执行出库失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 返回
    goBack() {
      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss" scoped>
.outbound-execute {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 140rpx;
}

.detail-container {
  padding: 20rpx;
}

.header-section {
  background: linear-gradient(135deg, #ff9a56 0%, #ff6b35 100%);
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(255, 154, 86, 0.3);

  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .order-title {
      font-size: 36rpx;
      font-weight: bold;
      color: white;
    }

    .status-badge {
      padding: 10rpx 20rpx;
      border-radius: 25rpx;
      background: rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(10rpx);
      border: 2rpx solid rgba(255, 255, 255, 0.3);

      .status-text {
        font-size: 26rpx;
        color: white;
        font-weight: 500;
      }
    }
  }

  .order-details {
    .detail-text {
      display: block;
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.9);
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.detail-section {
  .section-title {
    background: white;
    padding: 30rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    border-bottom: 2rpx solid #f0f0f0;
    margin-bottom: 20rpx;
    border-radius: 12rpx 12rpx 0 0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
}

.detail-card {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #f8f9fa;
    background-color: #fafbfc;

    .card-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .detail-count {
      font-size: 26rpx;
      color: #666;
    }
  }
}

.detail-list {
  .detail-item {
    border-bottom: 2rpx solid #f8f9fa;

    &:last-child {
      border-bottom: none;
    }

    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 30rpx 16rpx;
      background-color: #f8f9fa;

      .window-info {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }

      .quantity {
        font-size: 28rpx;
        color: #007aff;
        font-weight: 600;
      }
    }

    .item-content {
      padding: 20rpx 30rpx 24rpx;

      .detail-row {
        display: flex;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .detail-label {
          width: 140rpx;
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }

        .detail-value {
          flex: 1;
          font-size: 26rpx;
          color: #333;
        }
      }
    }
  }
}

.batch-section {
  .batch-item {
    border-top: 2rpx solid #f0f0f0;

    .batch-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      background: #f9f9f9;

      .batch-label {
        font-size: 26rpx;
        color: #333;
        font-weight: bold;
      }
    }

    .batch-inputs {
      padding: 30rpx;

      .field-group {
        display: flex;
        align-items: center;
        margin-bottom: 30rpx;

        .field-label {
          width: 120rpx;
          font-size: 28rpx;
          color: #333;
        }

        .warehouse-picker,
        .location-picker {
          flex: 1;

          .picker-display {
            padding: 20rpx;
            background: #f5f5f5;
            border-radius: 10rpx;
            font-size: 28rpx;
            color: #333;
          }
        }

        input {
          flex: 1;
          padding: 24rpx;
          background: white;
          border: 2rpx solid #e8e8e8;
          border-radius: 12rpx;
          font-size: 28rpx;
          color: #333;
          text-align: center;
          transition: all 0.3s ease;

          &:focus {
            border-color: #ff9a56;
            box-shadow: 0 0 0 4rpx rgba(255, 154, 86, 0.1);
          }
        }
      }
    }
  }
}

.detail-info {
  padding: 20rpx 30rpx;
  background: #fafafa;

  .info-text {
    display: block;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;

    &:last-child {
      margin-bottom: 0;
      color: #ff6b35;
      font-weight: bold;
    }
  }
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 30rpx;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.12);
  border-radius: 20rpx 20rpx 0 0;

  .summary-info {
    margin-bottom: 24rpx;
    text-align: center;
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #f0f2f5, #fff2e8);
    border-radius: 16rpx;

    .summary-text {
      font-size: 32rpx;
      color: #ff6b35;
      font-weight: bold;
    }
  }

  .action-buttons {
    display: flex;
    gap: 24rpx;

    .cu-btn {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 20rpx;
      font-size: 32rpx;
      border: none;
      font-weight: 600;
      transition: all 0.3s ease;

      &.bg-gray {
        background: #f5f5f5;
        color: #666;
        border: 2rpx solid #e8e8e8;

        &:active {
          background: #e8e8e8;
          transform: translateY(2rpx);
        }
      }

      &.bg-orange {
        background: linear-gradient(45deg, #ff9a56, #ff6b35);
        color: white;
        box-shadow: 0 6rpx 20rpx rgba(255, 154, 86, 0.4);

        &:active:not(:disabled) {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 16rpx rgba(255, 154, 86, 0.5);
        }

        &:disabled {
          background: #d9d9d9;
          color: #999;
          box-shadow: none;
        }
      }
    }
  }

  // 产品标题区域
  .product-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .product-title {
      flex: 1;

      .series-name {
        display: block;
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 6rpx;
      }

      .product-code {
        font-size: 26rpx;
        color: #666;
        background: #f8f9fa;
        padding: 4rpx 10rpx;
        border-radius: 6rpx;
      }
    }

    .available-badge {
      background: #ff6b35;
      padding: 8rpx 16rpx;
      border-radius: 16rpx;

      .available-text {
        font-size: 24rpx;
        color: white;
        font-weight: 500;
      }
    }
  }

  // 产品详情卡片
  .item-content {
    padding: 20rpx 30rpx 24rpx;

    .detail-row {
      display: flex;
      margin-bottom: 16rpx;

      &:last-child {
        margin-bottom: 20rpx;
      }

      .detail-label {
        width: 140rpx;
        font-size: 40rpx;
        color: #666;
        flex-shrink: 0;
        margin-right: 40rpx;
      }

      .detail-value {
        flex: 1;
        font-size: 26rpx;
        color: #333;
      }
    }
  }

  // 出库数量设置区域
  .quantity-section {
    .quantity-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;

      .quantity-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }

      .quantity-hint {
        font-size: 24rpx;
        color: #999;
      }
    }

    .quantity-control {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 20rpx;
      padding: 20rpx;
      background: white;
      border-radius: 12rpx;
      border: 2rpx solid #e9ecef;

      .quantity-btn {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        border: 2rpx solid #ff6b35;
        background: white;
        color: #ff6b35;
        font-size: 32rpx;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        &:not(:disabled):active {
          background: #ff6b35;
          color: white;
          transform: scale(0.95);
        }

        &:disabled {
          border-color: #ddd;
          color: #ccc;
          background: #f5f5f5;
        }
      }

      .quantity-input-field {
        width: 120rpx;
        height: 60rpx;
        text-align: center;
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        border: 2rpx solid #ddd;
        border-radius: 8rpx;
        background: white;

        &:focus {
          border-color: #ff6b35;
        }
      }
    }
  }
}
</style>